package cn.admin.configcenter.registry.service.client;

import cn.admin.configcenter.registry.pojo.PureClientInfo;
import cn.admin.configcenter.registry.service.ServerUtil;

import java.util.regex.Pattern;

public class ClientFilter implements Filter {

    private static final String PATTERN_STR = "^.*$";
    final Pattern dataIdPattern;
    final Pattern groupIdPattern;
    final Pattern ipPattern;
    Commond commond = null;

    ClientFilter(Pattern dataIdPattern,Pattern groupIdPattern,Pattern ipPattern) {
        this.dataIdPattern = dataIdPattern;
        this.groupIdPattern = groupIdPattern;
        this.ipPattern = ipPattern;
        initCommond();
    }


    private void initCommond() {
        if (PATTERN_STR.equals(this.dataIdPattern.toString()) && PATTERN_STR.equals(this.groupIdPattern.toString())) {
            this.commond = (dataId, groupId, hostId) -> ClientFilter.this.ipPattern.
                    matcher(ServerUtil.getIp(hostId)).matches();
        } else if (PATTERN_STR.equals(this.groupIdPattern.toString()) &&
                PATTERN_STR.equals(this.ipPattern.toString())) {
            this.commond = (dataId, groupId, hostId) -> ClientFilter.
                    this.dataIdPattern.matcher(dataId).matches();
        } else if (PATTERN_STR.equals(this.ipPattern.toString())) {
            this.commond = (dataId, groupId, hostId) -> ClientFilter.this.
                    dataIdPattern.matcher(dataId).matches() &&
                    ClientFilter.this.groupIdPattern.matcher(groupId).matches();
        } else {
            this.commond = (dataId, groupId, hostId) -> ClientFilter.
                    this.dataIdPattern.matcher(dataId).matches()
                    && ClientFilter.this.groupIdPattern.matcher(groupId).matches()
                    && ClientFilter.this.ipPattern.
                    matcher(ServerUtil.getIp(hostId)).matches();
        }
    }

    @Override
    public boolean accept(Object obj) {
        PureClientInfo pc = (PureClientInfo) obj;
        return this.dataIdPattern.matcher(pc.getDataId()).matches()
                && this.groupIdPattern.matcher(pc.getGroups().get(0)).matches()
                && this.ipPattern.matcher(ServerUtil.getIp(pc.getHostId()))
                .matches();
    }

    public boolean accept(String dataId,String groupId,String hostId) {
        return this.commond.filter(dataId,groupId,hostId);
    }
}
